package com.bookstore.spring.filter;

import com.bookstore.spring.util.MybatisSessionFactory;
import org.apache.ibatis.session.SqlSession;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by Admin on 2016/9/8.
 */
@WebFilter("/*")
public class TranactionFilter implements Filter{
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
       public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        SqlSession sqlSession=null;
        try{
            //1. 获取连接
            sqlSession= MybatisSessionFactory.getSession();
            //2. 把请求转给目标 Servlet
            filterChain.doFilter(servletRequest,servletResponse);
            //3. 提交事务
            sqlSession.commit();
        }catch (Exception e){
            e.printStackTrace();
            sqlSession.rollback();
            HttpServletResponse resp = (HttpServletResponse) servletResponse;
            HttpServletRequest req = (HttpServletRequest) servletRequest;
            resp.sendRedirect(req.getContextPath() + "/error.jsp");
        }finally {
            MybatisSessionFactory.closeSession();
        }

    }

    @Override
    public void destroy() {

    }
}
